package com.example.xViewChat.NettyClient.Handler;

import android.content.Intent;
import com.example.xViewChat.Bean.IntentBean;
import com.example.xViewChat.NettyClient.ConnectorManager;
import io.ganguo.chat.core.connetion.IMConnection;
import io.ganguo.chat.core.protocol.Commands;
import io.ganguo.chat.core.protocol.Handlers;
import io.ganguo.chat.core.transport.Header;
import io.ganguo.chat.core.transport.IMRequest;
import io.ganguo.chat.core.util.JacksonMapper;
import io.ganguo.chat.route.biz.entity.Message;
import io.ganguo.chat.route.biz.entity.User;
import io.ganguo.chat.route.server.dto.JsonDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * Created by hasee on 2016-03-28.
 */
public class OperationHandler extends AndroidHandler<IMRequest> {
    private Logger logger = LoggerFactory.getLogger(OperationHandler.class);

    @Override
    public short getId() {
        return Handlers.OPERATION;
    }

    @Override
    public void dispatch(IMConnection connection, IMRequest request) {
        Header header = request.getHeader();
        switch (header.getCommandId()) {
            case Commands.GET_PRESENCE_SUCCESS://获取一个人的动态
                onGetPresenceSuccess(connection, request);
                break;
            case Commands.GET_OFFMESSAGE_SUCCESS://获取离线消息
                onGetOffMessageSUCESS(connection, request);
                break;
            default:
                connection.close();
                break;
        }
    }

    private void onGetOffMessageSUCESS(IMConnection connection, IMRequest request) {
        JsonDto jsonDto = request.readEntity(JsonDto.class);
        List<Message> messages= JacksonMapper.readListValue(jsonDto.getJsonData(), Message.class);

        for(int i=0;i<messages.size();i++)
        {
            System.out.println(messages.get(i).toString());
        }
    }

    private void onGetPresenceSuccess(IMConnection connection, IMRequest request) {
        JsonDto jsonDto = request.readEntity(JsonDto.class);
        List<User> users=JacksonMapper.readListValue(jsonDto.getJsonData(), User.class);

        for(int i=0;i<users.size();i++){
            System.out.println(users.get(i).toString());
        }

        Intent intent = new Intent();
        intent.setAction(ConnectorManager.ACTION_REPLY_RECEIVED);
        IntentBean intentBean = new IntentBean();
        intentBean.setHeader(request.getHeader());
        intentBean.setEntity(jsonDto.getJsonData());
        intent.putExtra("intentBean", intentBean);
        context.sendBroadcast(intent);
    }
}
